package lc.二叉树.剑指Offer;

import utils.TreeNode;

/**
 * @description:
 * @author: qian
 * @createDate: 2021/10/31
 */
public class 剑指Offer68II_二叉树的最近公共祖先 {

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {

        if (root == null) return null;
        if (p.val == root.val || q.val == root.val) return root;
        TreeNode treeNode = lowestCommonAncestor(root.left, p, q);
        TreeNode treeNode1 = lowestCommonAncestor(root.right, p, q);
        if (treeNode1 != null && treeNode != null) {
            return root;
        }
        if (treeNode1 == null) return treeNode;
        if (treeNode == null) return treeNode1;
        return null;
    }
}
